package org.xhnews.ui;

import java.util.Vector;

import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

import org.xhnews.bo.RssBo;
import org.xhnews.to.RssChannel;

public class RssChannelListField extends ListField implements ListFieldCallback ,ScreenClosedListener,ShowWindow{
	private Vector _rsschannellist;
    final private RssChannelListField theField;
	public RssChannelListField() {
		theField=this;
		_rsschannellist = new Vector();
		setCallback(this);
		initialize();
	}
	public void notifyScreenClosed(Screen screen) {
        	reload();
  }
	public void initialize() {
		reload();
	}

	public void reload() {
		_rsschannellist = RssBo.getAllRssChannels();
		setSize(_rsschannellist.size());

	}

	public void drawListRow(ListField list, Graphics g, int index, int y, int w) {
		String text = ((RssChannel) _rsschannellist.elementAt(index)).getName();
		g.drawText(text, 0, y, 0, w);
	}

	public Object get(ListField list, int index) {
		return _rsschannellist.elementAt(index);
	}

	public int indexOfList(ListField list, String prefix, int string) {
		return _rsschannellist.indexOf(prefix, string);
	}

	public int getPreferredWidth(ListField list) {
		return Display.getWidth();
	}

	private void navigationToRssItemListScreen() {
		RssChannel rsschannel = (RssChannel) _rsschannellist
				.elementAt(getSelectedIndex());
		RssItemListScreen screen = new RssItemListScreen();
		screen.initialize(rsschannel);
		UiApplication.getUiApplication().pushScreen(screen);
	}

	protected boolean navigationClick(int status, int time) {
		navigationToRssItemListScreen();
		return true;
	}

	protected boolean keyChar(char key, int status, int time) {
		if (key == Characters.ENTER) {
			navigationToRssItemListScreen();
		}
		return true;
	}

	public void append() {
		UiApplication.getUiApplication().pushScreen(
				new AppEdtRssChnnlPopupScreen(theField));
	}

	public void edit() {
		UiApplication.getUiApplication().pushScreen(
				new AppEdtRssChnnlPopupScreen((RssChannel) _rsschannellist
						.elementAt(getSelectedIndex()), theField));
	}

	public void del() {
		UiApplication.getUiApplication().pushScreen(
				new DelRssChnnlPopupScreen((RssChannel) _rsschannellist
						.elementAt(getSelectedIndex()),theField));
	}


//	protected void paint(Graphics graphics) {
//		RaspberryLogger.getInstance().info("paint(Graphics graphics)");
//		int i = 0;
//		while (i < _rsschannellist.size()) {
//			drawListRow(this, graphics, i, i * getRowHeight(),
//					getPreferredWidth());
//			i++;
//		}
//	}

}
